package com.easylinkin.linkappapi.keywork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.keywork.utils.DateDealUtils;
import com.easylinkin.linkappapi.keywork.dto.SafeTableDto;
import com.easylinkin.linkappapi.keywork.dto.SafeTableRecordDto;
import com.easylinkin.linkappapi.keywork.entity.KeyworkList;
import com.easylinkin.linkappapi.keywork.entity.SafeTable;
import com.easylinkin.linkappapi.keywork.entity.SafeTableItem;
import com.easylinkin.linkappapi.keywork.entity.SafeTableRecord;
import com.easylinkin.linkappapi.keywork.mapper.KeyworkListMapper;
import com.easylinkin.linkappapi.keywork.mapper.SafeTableItemMapper;
import com.easylinkin.linkappapi.keywork.mapper.SafeTableMapper;
import com.easylinkin.linkappapi.keywork.mapper.SafeTableRecordMapper;
import com.easylinkin.linkappapi.keywork.service.SafeTableService;
import com.easylinkin.linkappapi.keywork.vo.SafeTableItemVo;
import com.easylinkin.linkappapi.keywork.vo.SafeTableRecordVo;
import com.easylinkin.linkappapi.keywork.vo.SafeTableVo;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2020-04-16
 */
@Service
@Slf4j
public class SafeTableServiceImpl extends ServiceImpl<SafeTableMapper, SafeTable> implements SafeTableService {


    @Resource
    private RedissonClient redisson;

    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private KeyworkListMapper keyworkListMapper;

    @Resource
    private SafeTableMapper safeTableMapper;

    @Resource
    private SafeTableItemMapper safeTableItemMapper;

    @Resource
    private SafeTableRecordMapper safeTableRecordMapper;


    @Override
    public IPage<SafeTableVo> selectPage(Page page, SafeTable safeTable) {
        safeTable.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return  safeTableMapper.selectTableListByPage(page,safeTable);
    }

    @Override
    public List<SafeTableVo> selectList(SafeTable safeTable) {
        safeTable.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<SafeTableVo> safeTableVoList = safeTableMapper.selectSafeTableList(safeTable);
        if (safeTableVoList.size() > 0){
            for (SafeTableVo safeTableVo:safeTableVoList){
                List<Map<String, Object>> mapList = new ArrayList<>();
                List<Map<String , Object>> userSignList = safeTableMapper.selcetTableSignUser(safeTableVo.getId());
                Integer tableStatus = 0; //表格状态
                for (Map<String , Object> mapTmp : userSignList){
                    Map<String, Object> map = new HashMap<>();
                    map.put("checkUser", mapTmp.get("checkUserName") == null ? "" : mapTmp.get("checkUserName").toString());
                    map.put("checkTime", mapTmp.get("checkTime") == null ? "" : mapTmp.get("checkTime").toString());
                    map.put("status", "填写");
                    tableStatus = mapTmp.get("tableStatus") == null ?0:Integer.valueOf(mapTmp.get("tableStatus").toString());
                    mapList.add(map);
                }
                if (tableStatus != 0){
                    Map<String, Object> map = new HashMap<>();
                    map.put("checkUser", userSignList.get(0).get("tableUserName") == null ? "" : userSignList.get(0).get("tableUserName").toString());
                    map.put("checkTime", userSignList.get(0).get("tableCheckTime") == null ? "" : userSignList.get(0).get("tableCheckTime").toString());
                    map.put("status",tableStatus == 1 ? "待签字":"已签字");
                    mapList.add(map);
                }
                safeTableVo.setUserSignList(mapList);
            }
        }
        return safeTableVoList;
    }

    @Override
    public Boolean addTable(SafeTable safeTable) {
        //添加主表信息
        KeyworkList keyworkList = keyworkListMapper.selectById(safeTable.getKeyworkId());
        if (null == safeTable.getKeyworkParentId()) { //如果前端未提交分类id，后台通过查询作业信息赋值
            safeTable.setKeyworkParentId(Long.valueOf(keyworkList.getParentId()));
        }
        if (StringUtils.isEmpty(safeTable.getTableName())){
            safeTable.setTableName(keyworkList.getContentName()+ DateDealUtils.changeToDayString(safeTable.getWorkTime())); //表名=作业内容+施工时间年月日
        }
        safeTable.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        safeTable.setTableTitle(keyworkList.getContentName() + "安全条件确认表");
        safeTable.setCheckOpinion(0); //检查状态为检查中
        safeTable.setTableStatus(0);//表状态为协作中
        safeTable.setCreateUserId(linkappUserContextProducer.getNotNullCurrent().getId());
        safeTable.setCreateTime(new Date());
        safeTable.setLatestModifyTime(new Date());

        if (baseMapper.insert(safeTable) != 1) {
            return false;
        } else {
            //添加记录表信息
            SafeTableItem safeTableItem = new SafeTableItem();
            safeTableItem.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
            safeTableItem.setKeyworkId(safeTable.getKeyworkId());
            List<SafeTableItemVo> safeTableItemVoList = safeTableItemMapper.selectSafeTableItemList(safeTableItem); //通过主表的作业内容id，查询出该作业对应额检查表项目
            if (safeTableItemVoList.size() > 0) {
                for (SafeTableItemVo safeTableItemVo : safeTableItemVoList) { //将检查项存入子表
                    SafeTableRecord safeTableRecord = new SafeTableRecord();

                    safeTableRecord.setTableId(safeTable.getId()); // 主表关联id
                    safeTableRecord.setItemId(safeTableItemVo.getId()); //对应的检查项id
                    safeTableRecord.setCheckResult(0); //检查结果默认为未检查
                    if (safeTableRecordMapper.insert(safeTableRecord) != 1) {
                        baseMapper.deleteById(safeTable.getId());
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public int updateTable(SafeTableDto safeTableDto) {
//        SafeTable safeTableUsed = baseMapper.selectById(safeTableDto.getId()); //查询原记录
//        safeTableUsed.setCheckOpinion(safeTableDto.getCheckOpinion()); //检查意见
//        safeTableUsed.setCreateUserId(linkappUserContextProducer.getNotNullCurrent().getId()); //检查提交
//        safeTableUsed.setCheckUserSign(safeTableDto.getCheckUserSign()); //检查人签名

        return baseMapper.updateById(safeTableDto);
    }

    @Override
    public int updateTableRecord(List<SafeTableRecordDto> safeTableRecordDtoList) {
        for (SafeTableRecordDto dto : safeTableRecordDtoList){
            dto.setCheckUserId(linkappUserContextProducer.getNotNullCurrent().getId());
            dto.setCheckTime(new Date());
            if (safeTableRecordMapper.updateById(dto) != 1){
                return 0;
            }
        }
        //校验子项是否填写完成，完成后变更主表状态
        SafeTableRecordDto dto = new SafeTableRecordDto();
        dto.setTableId(safeTableRecordDtoList.get(0).getTableId());
        dto.setCheckResult(0);
        List<SafeTableRecordVo> voList = safeTableRecordMapper.selectSafeTableRecordList(dto);
        if (voList.size() == 0){
            SafeTable  safeTable = safeTableMapper.selectById(dto.getTableId());
            safeTable.setTableStatus(1); //变更为待签字
            safeTableMapper.updateById(safeTable);
        }
        return 1;
    }


}
